package com.tp.base;

import java.util.List;
import java.util.Map;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.log.Log;
import com.tp.model.sys.SysMenu;
import com.tp.model.sys.SysUser;
import com.tp.service.MenuService;
import com.tp.service.UserService;
import com.tp.utils.Attr;
import com.tp.utils.DateUtils;
import com.tp.utils.HandlerUtils;
import com.tp.utils.NumberUtils;
import com.tp.utils.StrUtils;
import com.tp.utils.WebUtils;
/**
 * Controller 不能初始化
 * 
 */
public abstract class BaseController extends Controller {

	@Inject
	UserService service;
	
	@Inject
	MenuService menuService;

	protected static final Log log = Log.getLog(BaseController.class);

	protected void renderOk(String msg){
		renderJson(Ret.by("code", 0).set("msg", msg));
	}
	
	protected void renderFail(String msg){
		renderJson(Ret.by("code", 1).set("msg", msg));
	}
	
	protected <T> void renderCount(int count, List<T> list){
		renderJson(Ret.by("code", 0).set("count", count).set("data", list));
	}

	/**
	 * 获取前一个页面
	 * 
	 * @return
	 */
	protected String getPrePage() {
		return getRequest().getHeader("Referer");
	}

	/**
	 * 获取当前时间，保存创建时间使用
	 * 
	 * @return
	 */
	protected String getNow() {
		return DateUtils.getNow(DateUtils.DEFAULT_REGEX_YYYY_MM_DD_HH_MIN_SS);
	}

	protected <T> T handler(Class<T> modelClass) {
		Object o = null;
		try {
			o = modelClass.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return handler(o);
	}

	@SuppressWarnings("unchecked")
	protected <T> T handler(Object o) {
		if (o == null) {
			return null;
		}
		return (T) HandlerUtils.handler(getRequest(), o);
	}
	
	public void renderAuto(String view) {
		String path = getAutoPath(view);
		super.render(path);
	}

	public void redirectAuto(String view) {
		String path = getAutoPath(view);
		super.redirect(path);
	}

	protected String getAutoPath(String view) {
		String path = view;
		if (!view.startsWith("/")) {
			path = "/" + path;
		}
		path = path.replace("//", "/");
		return path;
	}

	public boolean isMoblie() {
		return getSessionAttr(Attr.SESSION_IS_MOILE);
	}

	/**
	 * 获取用户信息
	 * 
	 * @return
	 */
	public SysUser getSessionUser() {
		SysUser sysUser = getSessionAttr(Attr.SESSION_NAME);
		try {
			// 如果session没有，cookie有~那么就设置到Session
			if (sysUser == null) {
				String cookieContent = getCookie(Attr.SESSION_NAME);
				if (cookieContent != null) {
					String key = WebUtils.cookieDecrypt(cookieContent);
					if (StrUtils.isNotEmpty(key) && key.split(",").length == 2) {
						int userid = NumberUtils.parseInt(key.split(",")[0]);
						String password = key.split(",")[1];
						sysUser = new SysUser().findFirstByWhere(" where userid = ? and password = ? ", userid, password);
						if (sysUser != null)
							setSessionUser(sysUser);
					}
				}
			}
		} catch (Exception e) {
			// 异常cookie重新登陆
			removeSessionAttr(Attr.SESSION_NAME);
			removeCookie(Attr.SESSION_NAME);
			log.error("cooke user异常:", e);
			return null;
		}
		return sysUser;
	}

	/**
	 * 设置用户信息
	 * 
	 * @return
	 */
	public SysUser setSessionUser(SysUser user) {
		setSessionAttr(Attr.SESSION_NAME, user);
		// 设置cookie，用id+password作为
		String key = user.getUserId() + "," + user.getStr("password");
		String cookieContent = WebUtils.cookieEncrypt(key);
		setCookie(Attr.SESSION_NAME, cookieContent, 7 * 24 * 60 * 60);
		// 如果是管理员 设置菜单权限
		if (user.getUserType() == 1 || user.getUserType() == 2) {
			Map<Integer, List<SysMenu>> map = menuService.getAuthMap(user);
			// 注入菜单
			setSessionAttr("menu", map);
			// 不能访问的菜单
			setSessionAttr("nomenu", menuService.getNoAuthMap(map));
		}
		return user;
	}

	/**
	 * 删除用户信息
	 * 
	 * @return
	 */
	public void removeSessionUser() {
		removeSessionAttr(Attr.SESSION_NAME);
		// 删除cookie
		removeCookie(Attr.SESSION_NAME);
	}
	
	/**
	 * 获取登录用户ID
	 * @return
	 */
	public int getUID(){
		return  getSessionUser().getUserId();
	}
	
	public Paginator getPaginator() {
		Paginator paginator = new Paginator();
		Integer pageNo = getParaToInt("page");
		if (pageNo != null && pageNo > 0) {
			paginator.setPageNo(pageNo);
		}
		Integer pageSize = getParaToInt("limit");
		if (pageSize != null && pageSize > 0) {
			paginator.setPageSize(pageSize);
		}
		return paginator;
	}

	public Paginator getPaginator2(int size) {
		Paginator paginator = new Paginator(1, size);
		Integer pageNo = getParaToInt("page");
		if (pageNo != null && pageNo > 0) {
			paginator.setPageNo(pageNo);
		}
		Integer pageSize = getParaToInt("limit");
		if (pageSize != null && pageSize > 0) {
			paginator.setPageSize(pageSize);
		}
		return paginator;
	}

	public Object[] toArray(List<Object> list) {
		return list.toArray(new Object[list.size()]);
	}

	public BaseForm getBaseForm() {
		BaseForm form = super.getAttr("form");
		return form == null ? new BaseForm() : form;
	}

	/**
	 * 原始的GetModel方法
	 * 
	 * @param modelClass
	 * @return
	 */
	public <T> T getModelByOld(Class<T> modelClass) {
		return super.getModel(modelClass);
	}

	/**
	 * 覆盖原始方法，采用PAGE_MODEL_NAME做为前缀
	 * 表单参数
	 */
	@Override
	public <T> T getModel(Class<T> modelClass) {
		return super.getModel(modelClass, Attr.PAGE_MODEL_NAME);
	}

	/**
	 * 新GetModel方法，采用PAGE_ATTR_NAME，作为前缀
	 * 查询条件参数
	 * 
	 * @param modelClass
	 * @return
	 */
	public <T> T getModelByAttr(Class<T> modelClass) {
		return super.getModel(modelClass, Attr.PAGE_ATTR_NAME);
	}

	/**
	 * 新GetModel方法，采用PAGE_FORM_NAME，作为前缀
	 * 
	 * @param modelClass
	 * @return
	 */
	public <T> T getModelByForm(Class<T> modelClass) {
		return super.getBean(modelClass, Attr.PAGE_FORM_NAME);
	}
}
